package com.yonyougov.devops.cruxcisupport.server;

import com.yonyougov.devops.cruxcisupport.server.dto.*;
import com.yonyougov.devops.cruxcisupport.server.vo.*;
import com.yonyougov.devops.cruxcisupport.threadlocal.ErrorMessageThreadLocal;
import com.yonyougov.devops.fwc.api.dto.BaseResponseDto;
import com.yonyougov.devops.fwc.api.enums.BaseErrorCode;
import com.yonyougov.devops.fwc.core.controller.CrudController;
import com.yonyougov.devops.fwc.core.entity.Pagination;
import com.yonyougov.devops.fwc.core.service.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigInteger;
import java.util.List;


@Api(value = "服务器列表模块", tags = "服务器列表模块")
@RestController
@RequestMapping("/api/v2")
public class ServerController extends CrudController<ServerEntity, BigInteger> {

    private ServerService serverService;

    public ServerController(ServerService serverService) {
        this.serverService = serverService;
    }

    @Override
    public BaseService<ServerEntity, BigInteger> getService() {
        return serverService;
    }

    @ApiOperation(value = "前端server列表调用", notes = "可选择根据分页模糊查询")
    @PostMapping(value = "/server/u/page/like")
    @SneakyThrows
    public BaseResponseDto findUserPageLike(@RequestBody @Valid ServerPageLikeRequestDto request) {
        ServerPageLikeDto serverPageLikeDto = new ServerPageLikeDto();
        BeanUtils.copyProperties(request, serverPageLikeDto);

        Pagination<ServerPageLikeRespVoParams> pagination = serverService.findAllByParamsLike(serverPageLikeDto);

        BaseResponseDto result = BaseResponseDto.getSuccessInstance();
        result.put("totalCount", pagination.getTotalCount());
        result.put("data", pagination.getDatas());
        return result;
    }

    @ApiOperation(value = "前端server新增修改调用", notes = "新增修改server")
    @PostMapping(value = "/server")
    @SneakyThrows
    public BaseResponseDto addOrUpdateServer(@RequestBody @Valid ServerAddOrUpdateRequestDto request) {
        ServerEntity serverEntity = new ServerEntity();
        BeanUtils.copyProperties(request, serverEntity);
        if (serverEntity.getId() != null) {
            serverService.update(serverEntity);
        } else {
            serverService.add(serverEntity);
        }
        return BaseResponseDto.getSuccessInstance();
    }

    @ApiOperation(value = "前端server删除调用", notes = "根据用户主键逻辑删除")
    @PostMapping(value = "/server/u/delete/id")
    @SneakyThrows
    public BaseResponseDto deleteServerById(@RequestBody @Valid ServerDeleteRequestDto request) {
        //物理删除
        ServerEntity serverEntity = new ServerEntity();
        BeanUtils.copyProperties(request, serverEntity);
        serverService.deleteByPrimaryKey(serverEntity.getId());
        //物理删除
        return BaseResponseDto.getSuccessInstance();
    }

    @ApiOperation(value = "前端server拨测调用", notes = "server拨测调用")
    @PostMapping(value = "/server/u/dialing/")
    @SneakyThrows
    public BaseResponseDto dialingTest(@RequestBody @Valid ServerAddOrUpdateRequestDto request) {
        ServerEntity serverEntity = new ServerEntity();
        BeanUtils.copyProperties(request, serverEntity);
        serverService.dialingTest(serverEntity);
        return BaseResponseDto.getSuccessInstance();
    }

    @ApiOperation(value = "前端:用户关联server,新增时的列表渲染", notes = "根据用户id查询未绑定的用户关联server列表")
    @PostMapping(value = "/server/r/noLink/userId")
    public BaseResponseDto findNoLinkServerByUserId(@RequestBody @Valid NotLinkedServerByUserIdRequestDto request) {
        NoLinkServerDto pageParams = new NoLinkServerDto();
        BeanUtils.copyProperties(request, pageParams);

        Pagination<NoLinkServerRespVo> pagination = serverService.findNoLinkServerByUserId(pageParams);

        BaseResponseDto baseResponseDto = BaseResponseDto.getSuccessInstance();
        baseResponseDto.put("data", pagination.getDatas());
        baseResponseDto.put("totalCount", pagination.getTotalCount());
        return baseResponseDto;
    }

    @ApiOperation(value = "前端:用户关联server,新增时的列表渲染", notes = "根据用户id查询未绑定的用户关联server列表")
    @PostMapping(value = "/server/r/noLink/envId")
    public BaseResponseDto findNoLinkServerByEnvId(@RequestBody @Valid NotLinkedServerByEnvIdRequestDto request) {
        EnvNoLinkServerPageParams pageParams = new EnvNoLinkServerPageParams();
        BeanUtils.copyProperties(request, pageParams);
        int totalCount = serverService.findNoLinkServerByEnvIdCount(pageParams);
        List<NoLinkServerRespVo> dates = serverService.findNoLinkServerByEnvId(pageParams);
        BaseResponseDto baseResponseDto = BaseResponseDto.getSuccessInstance();
        baseResponseDto.put("data", dates);
        baseResponseDto.put("totalCount", totalCount);
        return baseResponseDto;
    }

    @ApiOperation(value = "批量更新服务器状态", notes = "批量更新server状态")
    @PostMapping(value = "/server/u/status")
    @SneakyThrows
    public BaseResponseDto batchUpdateServerStatus(@RequestBody @Valid ServerStatusRequestDto request) {
        serverService.batchUpdateServerStatus(request.getServerList());
        return BaseResponseDto.getSuccessInstance();
    }

    @ApiOperation(value = "CMD", notes = "执行命令")
    @PostMapping(value = "/server/cmd")
    @SneakyThrows
    public BaseResponseDto cmd(@RequestBody @Valid ExecuteCmdCommandRequestDto request) {
        ExecuteCmdCommandDto executeCmdCommandDto = new ExecuteCmdCommandDto();
        BeanUtils.copyProperties(request, executeCmdCommandDto);

        ExecuteCmdCommandVo executeCmdCommandVo = serverService.executeCmdCommand(executeCmdCommandDto);

        BaseResponseDto successInstance = BaseResponseDto.getSuccessInstance();
        successInstance.put("result", executeCmdCommandVo);
        return successInstance;
    }

    @ApiOperation(value = "注册主机", notes = "注册主机")
    @GetMapping(value = "/server/registr")
    @SneakyThrows
    public BaseResponseDto registr(@RequestParam("ip") String ip,
                                   @RequestParam("hostname") String hostname,
                                   @RequestParam("port") String port,
                                   @RequestParam("remark") String remark
                                   ) {
        serverService.registr(ip,hostname,port,remark);
        BaseResponseDto successInstance = BaseResponseDto.getSuccessInstance();
        successInstance.put("result", "success");
        return successInstance;
    }

    @ApiOperation(value = "刷新服务器状态", notes = "刷新服务器状态")
    @GetMapping(value = "/server/refreshstatus/{id}")
    @SneakyThrows
    public BaseResponseDto refreshServerStatus(@PathVariable(value = "id") BigInteger id) {
        serverService.refreshServerStatus(id);
        if(ErrorMessageThreadLocal.hasError()){
            BaseResponseDto failInstance = BaseResponseDto.getFailInstance(BaseErrorCode.SYS_ERROR);
            failInstance.setErrorMsg(ErrorMessageThreadLocal.getMessage());
            return failInstance;
        }
        BaseResponseDto successInstance = BaseResponseDto.getSuccessInstance();
        successInstance.put("result", "success");
        return successInstance;
    }

    @ApiOperation(value = "全文搜索")
    @PostMapping(value = "/server/search")
    public BaseResponseDto search(@RequestBody @Valid SearchDto searchDto) {
        BaseResponseDto successInstance = BaseResponseDto.getSuccessInstance();
        Pagination<ServerSearchVo> page = serverService.search(searchDto);
        successInstance.put("data", page.getDatas());
        successInstance.put("totalCount", page.getTotalCount());
        return successInstance;
    }
}
